package com.soft.mainsite.module.web.cms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.exception.SystemException;
import com.soft.mainsite.common.utils.*;
import com.soft.mainsite.module.city.dto.CityDto;
import com.soft.mainsite.module.city.service.CityService;
import com.soft.mainsite.module.staticstrategy.staticservice.StaticHtmlService;
import com.soft.mainsite.module.web.cms.service.SilderService;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.module.web.cms.vo.SiteQueryParams;
import com.soft.mainsite.module.web.cms.vo.TCmsSiteVo;
import com.soft.mainsite.module.web.system.service.RoleService;
import com.soft.mainsite.module.web.system.vo.UserVo;
import com.soft.mainsite.mybatis.mapper.*;
import com.soft.mainsite.mybatis.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:站点
 *
 * @author Jin
 * @create 2017-05-15
 **/
@Slf4j
@Service
public class SiteServiceImpl implements SiteService {

    @Value("${system.site.name}")
    private String siteName;

    @Autowired
    private TCmsSiteMapper siteMapper;

    @Autowired
    private TCmsUserSiteMapper userSiteMapper;

    @Autowired
    private TCmsCategoryMapper categoryMapper;

    @Autowired
    private TSysUserMapper sysUserMapper;

    @Autowired
    private TCmsContentMapper contentMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SilderService silderService;

    @Autowired
    private StaticHtmlService staticHtmlService;

    @Autowired
    private CityService cityService;


    @Override
    public String save(TCmsSite pojo) {
        return null;
    }

    @Override
    public String update(TCmsSite pojo) {
        return null;
    }

    @Override
    public String delete(Integer[] ids) {
        if (ids != null) {
            for (Integer id : ids) {
                if (id == 1) {
                    return JsonUtil.toError("主站点不能删除");
                }
                // 删除一切与当前站点相关联的内容
                siteMapper.deleteByPrimaryKey(id);
                userSiteMapper.deleteBySiteId(id);
                TCmsCategory category = new TCmsCategory();
                category.setSiteId(id);
                categoryMapper.delete(category);
                // 删除站点相关的栏内容
                TCmsContent content = new TCmsContent();
                content.setSiteId(id);
                contentMapper.delete(content);
            }
            return JsonUtil.toSuccess("操作成功", "site-tab", false);
        }
        return JsonUtil.toError("操作失败");
    }


    @Override
    public TCmsSite findById(Integer id) {
        return siteMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TCmsSite> findList(TCmsSite pojo) {
        return siteMapper.select(pojo);
    }

    @Override
    public List<TCmsSite> findAll() {
        return siteMapper.selectAll();
    }

    @Override
    public PageInfo<TCmsSite> page(Integer pageNumber, Integer pageSize, TCmsSite pojo) {
        PageHelper.startPage(pageNumber, pageSize);
        return new PageInfo<>(findList(pojo));
    }

    @Override
    public PageInfo<TCmsSite> page(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        return new PageInfo<>(findAll());
    }

    @Transactional(transactionManager = "masterTransactionManager", rollbackFor = Exception.class)
    @Override
    public String save(TCmsSiteVo pojo) {
        if (StringUtils.isNotBlank(pojo.getDomain()) && pojo.getDomain().contains(CmsConst.PUNCTUATION_POINT)) {
            // 截取域名中第一个"."前面的字符串
            pojo.setSiteKey(pojo.getDomain().substring(0, pojo.getDomain().indexOf(".")));
        }
        pojo.setIsMobile(true);
        pojo.setStatus(true);
        pojo.setTemplate("web");
        pojo.setMobileTpl("mobile");
        String[] userIds = StrUtil.excludeRepeatStr(pojo.getUserIds());
        if (siteMapper.insertSelective(pojo) > 0) {
            // 更新用户和站点的关系
            this.userSiteUpdate(userIds, pojo);
            // 初始化首页幻灯
            this.initSilder(pojo);
            // 静态化首页城市
            try {
                staticHtmlService.common(CmsConst.MAIN_SITE_ID, "common/index/index_city", CmsConst.TPL_TYPE_MOBILE);
                staticHtmlService.triggerStatic(pojo.getSiteId(), "common/index/index_city", CmsConst.TPL_TYPE_MOBILE, false);
            } catch (Exception e) {
                log.error("静态化首页城市失败", e);
            }

            return JsonUtil.toSuccess("操作成功", "site-tab", true);
        }
        return JsonUtil.toError("操作失败");
    }


    @Transactional(transactionManager = "masterTransactionManager", rollbackFor = Exception.class)
    @Override
    public String update(TCmsSiteVo pojo) {
        if (StringUtils.isNotBlank(pojo.getDomain()) && pojo.getDomain().contains(CmsConst.PUNCTUATION_POINT)) {
            pojo.setSiteKey(pojo.getDomain().substring(0, pojo.getDomain().indexOf(".")));
        }

        String[] userIds = StrUtil.excludeRepeatStr(pojo.getUserIds());
        if (siteMapper.updateByPrimaryKeySelective(pojo) > 0) {
            // 如果是更新就先清空当前站点与用户的关联
            userSiteMapper.deleteBySiteId(pojo.getSiteId());
            // 重新遍历添加
            this.userSiteUpdate(userIds, pojo);
            // 静态化首页城市
            try {
                staticHtmlService.common(CmsConst.MAIN_SITE_ID, "common/index/index_city", CmsConst.TPL_TYPE_MOBILE);
                staticHtmlService.triggerStatic(pojo.getSiteId(), "common/index/index_city", CmsConst.TPL_TYPE_MOBILE, false);
            } catch (Exception e) {
                log.error("静态化首页城市失败", e);
            }

            return JsonUtil.toSuccess("操作成功", "site-tab", true);
        }
        return JsonUtil.toError("操作失败");
    }

    /**
     * 更新用户和站点之间的关系
     *
     * @param userIds
     * @param pojo
     */
    private void userSiteUpdate(String[] userIds, TCmsSiteVo pojo) {
        if (userIds != null && userIds.length > 0) {
            for (String userId : userIds) {
                if (CmsUtil.isNullOrEmpty(sysUserMapper.selectByPrimaryKey(Integer.parseInt(userId)))) {
                    throw new SystemException("管理员[" + userId + "]不存在！");
                }
                TCmsUserSite userSite = new TCmsUserSite();
                userSite.setSiteId(pojo.getSiteId());
                userSite.setUserId(Integer.parseInt(userId));
                userSiteMapper.insert(userSite);
            }
        }
    }

    @Override
    public TCmsSiteVo findVoById(Integer id) {
        TCmsSiteVo siteVo = siteMapper.selectSiteVoById(id);
        List<TCmsUserSite> userSites = userSiteMapper.selectBySiteId(id);
        String userIds = "";
        if (userSites != null && userSites.size() > 0) {
            for (TCmsUserSite userSite : userSites) {
                userIds += userSite.getUserId() + ",";
            }
        }
        siteVo.setUserIds(userIds.length() > 0 ? userIds.substring(0, userIds.length() - 1) : userIds);
        siteVo.setProvinceCityName(this.getProvinceCityName(siteVo));
        return siteVo;
    }

    @Override
    public TCmsSite findBySiteKey(String key) {
        TCmsSite site = new TCmsSite();
        site.setSiteKey(key);
        return siteMapper.selectOne(site);
    }

    @Override
    public String change(UserVo userVo, Integer siteId) {
        HttpSession session = ControllerUtil.getHttpSession();
        TCmsSite site = siteMapper.selectByPrimaryKey(siteId);
        if (CmsUtil.isNullOrEmpty(site)) {
            return JsonUtil.toError("当前站点不存在！");
        }
        userVo.setSiteId(site.getSiteId());
        userVo.setSiteName(site.getSiteId() == 0 ? this.siteName : site.getSiteName());
        /*更新session*/
        session.setAttribute(CmsConst.SITE_USER_SESSION_KEY, userVo);
        return JsonUtil.toSuccess("站点切换成功，请刷新当前页面！", "site-tab", false);
    }


    @Override
    public TCmsSite findByDomain(String domain) {
        TCmsSite site = new TCmsSite();
        site.setDomain(domain);
        return siteMapper.selectOne(site);
    }


    @Override
    public TCmsSite findByCityCode(Integer cityCode, Integer siteId) {
        TCmsSite site = new TCmsSite();
        site.setCityCode(cityCode);
        TCmsSite tCmsSite = siteMapper.selectOne(site);
        if (tCmsSite != null && tCmsSite.getSiteId().equals(siteId)) {
            return null;
        } else {
            return tCmsSite;
        }
    }

    @Override
    public List<TCmsSite> findSiteStaticByStatus(String[] siteIds, Integer staticStatus) {
        return siteMapper.findSiteStaticByStatus(siteIds, staticStatus);
    }

    @Override
    public Map<String, Object> findSiteStatic(String[] siteIds) {

        Map<String, Object> result = new HashMap<>(16);
        List<TCmsSite> successSite = new ArrayList<>();
        List<TCmsSite> errorSite = new ArrayList<>();
        List<TCmsSite> siteStatic = siteMapper.findSiteStatic(siteIds);

        siteStatic.forEach(item -> {
            if (CmsConst.SITE_STATIC_SUCCESS.equals(item.getStaticStatus())) {
                successSite.add(item);
            } else if (CmsConst.SITE_STATIC_ERROR.equals(item.getStaticStatus())) {
                errorSite.add(item);
            }
        });

        result.put("successSite", successSite);
        result.put("errorSite", errorSite);
        return result;
    }

    @Override
    public void updateStaticStatus(Integer siteId, boolean staticStatus) {
        Integer flag = staticStatus ? CmsConst.SITE_STATIC_SUCCESS : CmsConst.SITE_STATIC_ERROR;
        siteMapper.updateStaticStatus(siteId, flag);
    }

    @Override
    public List<TCmsSite> findAllSiteStaticByStatus(Integer staticStatus) {
        return siteMapper.findAllSiteStaticByStatus(staticStatus);
    }

    @Override
    public PageInfo<TCmsSiteVo> pageSiteVoListByConditions(Integer pageNumber, Integer pageSize, SiteQueryParams queryParams, UserVo userVo) {
        // 查询用户角色列表
        List<TSysRole> byUserId = roleService.findByUserId(userVo.getUserId());
        queryParams.setUserId(userVo.getUserId());
        PageHelper.startPage(pageNumber, pageSize);
        for (TSysRole tSysRole : byUserId) {
            // 判断用户是否是超级管理员  或者是运营超管
            // 如果是查询所有站点
            if ("superAdmin".equals(tSysRole.getRolename()) || "operationAdmin".equals(tSysRole.getRolename())) {
                queryParams.setIsSuper(true);
                return new PageInfo<>(pageSiteVoListByConditions(queryParams));
            }
        }
        // 如果不是查询自己管理的站点
        queryParams.setIsSuper(false);
        return new PageInfo<>(pageSiteVoListByConditions(queryParams));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveMore(Integer siteNum) {
        List<TCmsSite> siteList = new ArrayList<>();
        for (int i = 0; i < siteNum; i++) {
            TCmsSite site = new TCmsSite();
            site.setSiteName("批量创建子站点");
            site.setTemplate("web");
            site.setMobileTpl("mobile");
            site.setDomain("127.0.0.1");
            if (StringUtils.isNotBlank(site.getDomain()) && site.getDomain().contains(".")) {
                site.setSiteKey(site.getDomain().substring(0, site.getDomain().indexOf(".")));
            }
            site.setStatus(true);
            site.setIsMobile(true);
            siteList.add(site);
        }
        int i = siteMapper.insertMore(siteList);
        if (i > 0) {
            for (TCmsSite tCmsSite : siteList) {
                // 批量初始化首页幻灯
                this.initSilder(tCmsSite);
            }
        }
        return JsonUtil.toSuccess("成功批量添加" + i + "条数据", "site-tab", true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String deleteMore() {
        List<Integer> integers = siteMapper.selectNoCityCodeSiteIds(CmsConst.MAIN_SITE_ID);
        int i = siteMapper.deleteMore(CmsConst.MAIN_SITE_ID);
        if (i > 0) {
            // 删除批量创建的首页幻灯
            log.info("删除批量创建的首页幻灯 {}", integers);
            silderService.deleteMoreBySiteId(integers);
        }
        return JsonUtil.toSuccess("成功删除" + i + "条数据", "site-tab", false);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String initInputMore() {
        List<TCmsSite> siteList = new ArrayList<>();
        List<CityDto> cityList = cityService.getProviceCityList();
        int i = 2;
        for (CityDto cityDto : cityList) {
            String cityNamePinYin = PinyinUtil.convertLower(cityDto.getCityName());
            TCmsSite site = new TCmsSite();
            site.setSiteId(i);
            site.setSiteName(cityDto.getCityName().concat("站点"));
            site.setTemplate("web");
            site.setMobileTpl("mobile");
            site.setDomain(cityNamePinYin.concat(".unisiot.com"));
            site.setCityCode(cityDto.getCityCode());
            site.setProvinceCode(cityDto.getCityParentCode());
            site.setSiteKey(cityNamePinYin);
            site.setSiteType(3);
            site.setSortId(1);
            site.setStatus(true);
            site.setIsMobile(true);
            siteList.add(site);
            i++;
        }
        int j = siteMapper.insertInitMore(siteList);
        return JsonUtil.toSuccess("成功初始化添加" + j + "条数据", "site-tab", false);
    }

    private List<TCmsSiteVo> pageSiteVoListByConditions(SiteQueryParams queryParams) {
        List<TCmsSiteVo> tCmsSiteVos = siteMapper.pageSiteVoListByConditions(queryParams);
        for (TCmsSiteVo siteVo : tCmsSiteVos) {
            siteVo.setProvinceCityName(this.getProvinceCityName(siteVo));
        }
        return tCmsSiteVos;
    }

    /**
     * 省份城市显示
     *
     * @param siteVo
     * @return
     */
    private String getProvinceCityName(TCmsSiteVo siteVo) {
        if (StringUtils.isBlank(siteVo.getProvinceName())) {
            return null;
        }
        if (siteVo.getProvinceName().equals(siteVo.getCityName())) {
            siteVo.setProvinceCityName(siteVo.getProvinceName());
        } else {
            siteVo.setProvinceCityName(siteVo.getProvinceName().concat(" ").concat(siteVo.getCityName()));
        }
        return siteVo.getProvinceCityName();
    }

    /**
     * 创建站点时初始化首页幻灯
     *
     * @param site
     * @return
     */
    private int initSilder(TCmsSite site) {
        // 查询主站首页幻灯 4条
        log.info("初始化首页幻灯，站点id{}", site.getSiteId());
        List<TCmsAdSilder> tCmsAdSilderList = silderService.findInitSilder();
        if (tCmsAdSilderList.isEmpty()) {
            log.info("初始化首页幻灯失败！！！主站没有需要创建的幻灯！！");
            return 0;
        }
        List<TCmsAdSilder> adSilderList = new ArrayList<>();
        for (TCmsAdSilder tCmsAdSilder : tCmsAdSilderList) {
            TCmsAdSilder adSilder = new TCmsAdSilder();
            BeanUtils.copyProperties(tCmsAdSilder, adSilder);
            adSilder.setId(null);
            adSilder.setSiteId(site.getSiteId());
            adSilder.setPushId(tCmsAdSilder.getId());
            adSilderList.add(adSilder);
        }
        return silderService.saveMoreSilder(adSilderList);
    }
}
